<template>
  <div v-if="showStatus" class="backend-status" :class="statusClass">
    <el-icon><InfoFilled /></el-icon>
    <span>{{ statusMessage }}</span>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'

const showStatus = ref(false)
const statusClass = ref('')
const statusMessage = ref('')

// 检查后端状态
const checkBackendStatus = async () => {
  try {
    // 首先尝试健康检查端点
    let response = await fetch('http://localhost:9090/api/health', {
      method: 'GET',
      signal: AbortSignal.timeout(3000)
    })
    
    // 如果健康检查端点不存在，尝试根路径
    if (!response.ok && response.status === 404) {
      response = await fetch('http://localhost:9090/', {
        method: 'GET',
        signal: AbortSignal.timeout(3000)
      })
    }
    
    if (response.ok) {
      showStatus.value = true
      statusClass.value = 'success'
      statusMessage.value = '✅ 后端服务正常运行'
      
      // 3秒后隐藏成功消息
      setTimeout(() => {
        showStatus.value = false
      }, 3000)
    } else {
      showStatus.value = true
      statusClass.value = 'warning'
      statusMessage.value = '⚠️ 后端服务异常'
    }
  } catch (error) {
    showStatus.value = true
    statusClass.value = 'info'
    statusMessage.value = 'ℹ️ 后端服务不可用'
  }
}

onMounted(() => {
  // 延迟检查，避免影响页面加载
  setTimeout(checkBackendStatus, 2000)
  
  // 定期检查后端状态
  const interval = setInterval(checkBackendStatus, 30000) // 每30秒检查一次
  
  onUnmounted(() => {
    clearInterval(interval)
  })
})
</script>

<style scoped>
.backend-status {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 9999;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.backend-status.info {
  background-color: #e1f3ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.backend-status.warning {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.backend-status.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}
</style>
